package com.cqywc.cjadmin.service.impl;

import java.util.List;

import javax.validation.constraints.Email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cqywc.cjadmin.mapper.AdminMapper;
import com.cqywc.cjadmin.pojo.Admin;
import com.cqywc.cjadmin.pojo.AdminExample;
import com.cqywc.cjadmin.service.AdminSerivce;
import com.cqywc.cjadmin.service.ReturnSerivice;
import com.cqywc.cjadmin.utils.BaseUtils;

@Service
public class AdminServiceImpl  implements AdminSerivce{
	

	
	@Autowired
	private AdminMapper adminMapper;
	
	@Override
	public ReturnSerivice adminLists(ReturnSerivice returnSerivce,String usernmae) {
		//查询总条数
		AdminExample example=new  AdminExample();
		if(usernmae !=null && !usernmae.equals("")) {
			example.createCriteria().andUsernameLike("%"+usernmae+"%");
		}
		int count =adminMapper.countByExample(example);
		example.setOrderByClause("id desc");
		
		example.setPageIndex((returnSerivce.getPage()-1)*returnSerivce.getLimit());
		example.setPageSize(returnSerivce.getLimit());
		
		List<Admin> lists = adminMapper.selectByExample(example);
		returnSerivce.setLists(lists);
		returnSerivce.setCount(count);
		return returnSerivce;
	}

	@Override
	public int saveAdmin(Admin admin) throws Exception {
		AdminExample example =new AdminExample();
		example.createCriteria().andUsernameEqualTo(admin.getUsername());
		int count = adminMapper.countByExample(example);
		if(count>0) {
			throw new Exception("用户名已经存在");
		}
		int salt=(int)((Math.random()+1)*1000);
		admin.setSalt(Integer.toString(salt));
		admin.setPassword(BaseUtils.getPassword(admin.getSalt(), admin.getPassword()));
		admin.setCreateTime((int)(System.currentTimeMillis()/1000));
		admin.setUpdateTime(admin.getCreateTime());
		admin.setDeleteTime(0);
		int row = adminMapper.insertSelective(admin);
		return row;
	}
	
	public int updateAdmin(Admin admin) throws Exception {
		AdminExample example =null;
		Admin oldAdmin=adminMapper.selectByPrimaryKey(admin.getId());
		if(oldAdmin==null) {
			throw new Exception("非法操作");
		}
		if(!oldAdmin.getUsername().equals(admin.getUsername())) {
			example =new AdminExample();
			example.createCriteria().andUsernameEqualTo(admin.getUsername());
			int count = adminMapper.countByExample(example);
			if(count>0) {
				throw new Exception("用户名已经存在");
			}
		}
		int row = adminMapper.updateByPrimaryKeySelective(admin);
		return row;
	}
	
	
	@Override
	public Admin getAdminById(Integer id) throws Exception {
		
		Admin admin = adminMapper.selectByPrimaryKey(id);
		
		if(admin==null) {
			throw new Exception("管理员不存在");
		}
		
		return admin;
	}

}
